<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>编辑报表</span>
        <el-button style="float: right;" size="mini" @click="handleReturn">
          <i class="el-icon-back"></i> 返回
        </el-button>
      </div>

      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="报表编码" prop="reportCode">
          <el-input v-model="form.reportCode" placeholder="请输入报表编码" style="width: 400px" maxlength="64" />
        </el-form-item>
        <el-form-item label="报表名称" prop="reportName">
          <el-input v-model="form.reportName" placeholder="请输入报表名称" style="width: 400px" maxlength="100" />
        </el-form-item>
        <el-form-item label="报表类型" prop="reportType">
          <el-select v-model="form.reportType" placeholder="请选择报表类型" style="width: 400px">
            <el-option
              v-for="dict in dict.type.report_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据源" prop="dataSource">
          <el-select v-model="form.dataSource" placeholder="请选择数据源" style="width: 400px">
            <el-option
              v-for="ds in datasourceOptions"
              :key="ds.dsId"
              :label="ds.dsName"
              :value="ds.dsId.toString()"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属分类" prop="categoryIds">
          <el-select v-model="categoryIds" multiple placeholder="请选择报表分类" style="width: 400px">
            <el-option 
              v-for="item in categoryOptions" 
              :key="item.categoryId" 
              :label="item.categoryName" 
              :value="item.categoryId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="权限标识" prop="permissionCode">
          <el-input v-model="form.permissionCode" placeholder="请输入权限标识" style="width: 400px" maxlength="100" />
        </el-form-item>
        <el-form-item label="状态" prop="reportStatus">
          <el-radio-group v-model="form.reportStatus">
            <el-radio
              v-for="dict in dict.type.common_status"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入报表说明"
            maxlength="500"
            style="width: 400px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">提交</el-button>
          <el-button type="success" @click="handleDesign">设计报表</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { listDatasource } from "@/api/report/datasource";
import { getReport, updateReport } from "@/api/report/report";
import { getCategoryTree, getReportByCategory, relateCategory } from "@/api/report/category";

export default {
  name: "EditReport",
  dicts: ['report_type', 'common_status'],
  data() {
    return {
      // 报表ID
      reportId: undefined,
      // 表单数据
      form: {
        reportId: undefined,
        reportCode: '',
        reportName: '',
        reportType: '0',
        dataSource: '',
        reportStatus: '0',
        permissionCode: '',
        remark: ''
      },
      // 表单校验规则
      rules: {
        reportCode: [
          { required: true, message: "报表编码不能为空", trigger: "blur" },
          { min: 2, max: 64, message: '报表编码长度必须在2到64个字符之间', trigger: 'blur' }
        ],
        reportName: [
          { required: true, message: "报表名称不能为空", trigger: "blur" },
          { min: 2, max: 100, message: '报表名称长度必须在2到100个字符之间', trigger: 'blur' }
        ],
        reportType: [
          { required: true, message: "报表类型不能为空", trigger: "change" }
        ],
        dataSource: [
          { required: true, message: "数据源不能为空", trigger: "change" }
        ]
      },
      // 数据源选项
      datasourceOptions: [],
      // 分类选项
      categoryOptions: [],
      // 已选分类
      categoryIds: []
    };
  },
  created() {
    this.reportId = this.$route.params.id;
    this.loadDatasources();
    this.getReportInfo();
    this.loadCategories();
    this.getReportCategories();
  },
  methods: {
    // 加载数据源选项
    loadDatasources() {
      listDatasource({ pageSize: 100 }).then(response => {
        this.datasourceOptions = response.rows;
      });
    },
    // 加载分类树
    loadCategories() {
      getCategoryTree().then(response => {
        this.transformCategoryData(response.data);
      });
    },
    // 转换分类数据为平铺结构
    transformCategoryData(data, parentPath = '') {
      if (!data) return;
      
      data.forEach(item => {
        const path = parentPath ? `${parentPath} / ${item.categoryName}` : item.categoryName;
        
        // 添加到分类列表
        this.categoryOptions.push({
          categoryId: item.categoryId,
          categoryName: path
        });
        
        // 递归处理子分类
        if (item.children && item.children.length > 0) {
          this.transformCategoryData(item.children, path);
        }
      });
    },
    // 获取报表所属分类
    getReportCategories() {
      // 由于API没有直接获取报表所属分类的方法，这里使用一个替代方案
      // 先从所有分类中获取包含此报表的分类
      if (!this.reportId) return;
      
      // 这里假设分类API可以获取到分类下的报表
      getCategoryTree().then(response => {
        const categoryIds = [];
        
        // 遍历所有分类，查找包含当前报表的分类
        const findReportInCategory = (categories) => {
          if (!categories) return;
          
          categories.forEach(category => {
            // 从分类中获取报表列表
            getReportByCategory(category.categoryId).then(res => {
              const reports = res.rows || [];
              // 检查当前报表是否在这个分类下
              const found = reports.some(report => report.reportId === parseInt(this.reportId));
              if (found) {
                categoryIds.push(category.categoryId);
                this.categoryIds = [...categoryIds];
              }
            });
            
            // 递归检查子分类
            if (category.children && category.children.length > 0) {
              findReportInCategory(category.children);
            }
          });
        };
        
        findReportInCategory(response.data);
      });
    },
    // 获取报表信息
    getReportInfo() {
      getReport(this.reportId).then(response => {
        this.form = response.data;
      });
    },
    // 提交表单
    handleSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          // 更新报表基本信息
          updateReport(this.form).then(response => {
            // 更新报表分类关联
            relateCategory({
              reportId: this.reportId,
              categoryIds: this.categoryIds || []
            }).then(() => {
              this.$modal.msgSuccess("修改成功");
              this.handleReturn();
            }).catch(() => {
              this.$modal.msgSuccess("报表信息更新成功，但分类关联失败");
              this.handleReturn();
            });
          });
        }
      });
    },
    // 设计报表
    handleDesign() {
      this.$refs.form.validate(valid => {
        if (valid) {
          updateReport(this.form).then(response => {
            // 更新报表分类关联
            relateCategory({
              reportId: this.reportId,
              categoryIds: this.categoryIds || []
            }).then(() => {
              this.$modal.msgSuccess("保存成功，正在跳转到设计页面");
              this.$router.push({ path: `/report/design?reportId=${this.reportId}` });
            }).catch(() => {
              this.$modal.msgSuccess("报表信息更新成功，正在跳转到设计页面");
              this.$router.push({ path: `/report/design?reportId=${this.reportId}` });
            });
          });
        }
      });
    },
    // 取消操作
    handleCancel() {
      this.handleReturn();
    },
    // 返回列表
    handleReturn() {
      this.$router.push({ path: '/report/list' });
    }
  }
};
</script>

<style scoped>
.preview-container {
  min-height: 400px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 20px;
}
.empty-preview {
  min-height: 400px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #909399;
  font-size: 14px;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
}
.param-header {
  margin-bottom: 15px;
  text-align: right;
}
</style> 